from flask import redirect, url_for, render_template, request
from flask_login import login_user, login_required, logout_user

# 登录视图函数
from web import custom
from web.vo.LoginForm import LoginForm
from web.vo.User import User


@custom.route('/login', methods=['GET', 'POST'])
def login():
    next = request.args.get('next')
    form = LoginForm()
    emsg = None
    if form.validate_on_submit():
        user_name = form.username.data
        password = form.password.data
        user_info = User.get(user_name)  # 从用户数据中查找用户记录
        if user_info is None:
            emsg = "用户名或密码密码有误"
        else:
            if user_info.verify_password(password):  # 校验密码
                login_user(user_info)  # 创建用户 Session
                # 如果用户访问的登录页面后没有地址或者为非法地址都跳转到首页
                if not next or not next.startswith('/'):
                    next = url_for('custom.index')
                return redirect(next)
            else:
                emsg = "用户名或密码密码有误"

    return render_template('login.html', form=form, emsg=emsg)


@custom.route('/logout')  # 登出
@login_required
def logout():
    logout_user()
    return redirect(url_for('custom.login'))
